package com.it.water.controller.ImageController;

import com.it.water.common.Result;
import com.it.water.entity.DataEntity.Image;
import com.it.water.service.ImageRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/image")
public class ImageController {

    // 假设有一个名为 ImageRepository 的数据库操作接口
    @Autowired
    private ImageRepository imageRepository;

    @PostMapping("/uploadImage")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 保存图片到服务器
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            // 保存图片的路径
            Path path = Paths.get("D:\\files\\" + fileName);
            Files.write(path, file.getBytes());

            // 将路径和名称保存到数据库
            Image imageEntity = new Image();
            imageEntity.setImagePath(path.toString());
            imageEntity.setName(fileName);
            // imageRepository.save(imageEntity);

            return Result.success();
        } catch (IOException e) {
            return Result.error("发送错误");
        }
    }
}
